package logic

import (
	"context"
	"fmt"
	//##MODIFY_TIME!"time"

	//##ROW_STATUS!"team.wphr.vip/technology-group/erp/erp-service-go/common/consts"
	"team.wphr.vip/technology-group/erp/erp-service-go/common/handlers/mysql"
	"team.wphr.vip/technology-group/erp/erp-service-go/common/util"
	"team.wphr.vip/technology-group/erp/erp-service-go/idl/exterr"
	"team.wphr.vip/technology-group/erp/erp-service-go/idl/proto"
	"team.wphr.vip/technology-group/erp/erp-service-go/modules/GO_SERVICE_MODULE_LOWER/model"
	gormV2 "gorm.io/gorm"
)

var UPPER_GO_SERVICE_MODULE_HUMPLogicInstance UPPER_GO_SERVICE_MODULE_HUMPLogic

type UPPER_GO_SERVICE_MODULE_HUMPLogic struct {
}

//GetUPPER_GO_SERVICE_MODULE_HUMPDetail GO_SERVICE_MODULE_DESC - 详情
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) GetUPPER_GO_SERVICE_MODULE_HUMPDetail(ctx context.Context, req *proto.UPPER_GO_SERVICE_MODULE_HUMPDetailReq) (data *proto.UPPER_GO_SERVICE_MODULE_HUMPDetailDataResp, err error) {
	if req.Id <= 0 {
		err = exterr.New(exterr.E_PARAM_DROP)
		return
	}
	client := mysql.ClientV2.Model(&model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{})
	//##ROW_STATUS!client = client.Scopes(util.WithRowStatusNormalV2)
	if len(req.ManagerIds) > 0 {
		client = client.Where("manager in (?)", req.ManagerIds)
	}
	modelEntity := model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{}
	result := client.Where("id = ?", req.Id).First(&modelEntity)

	if result.Error == gormV2.ErrRecordNotFound {
		err = util.FormatAuthError(req.ManagerIds)
		return
	}
	if result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_SELECT_ERROR)
		return
	}
	data = this.formatDetailData(&modelEntity)
	return
}

//GetUPPER_GO_SERVICE_MODULE_HUMPList GO_SERVICE_MODULE_DESC - 列表
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) GetUPPER_GO_SERVICE_MODULE_HUMPList(ctx context.Context, req *proto.UPPER_GO_SERVICE_MODULE_HUMPListReq) (data *proto.UPPER_GO_SERVICE_MODULE_HUMPListDataResp, err error) {
	data = &proto.UPPER_GO_SERVICE_MODULE_HUMPListDataResp{}
	client := mysql.ClientV2.Model(&model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{})
	//##ROW_STATUS!client = client.Scopes(util.WithRowStatusNormalV2)

	if req.Id > 0 {
		client = client.Where("id = ?", req.Id)
	}
	if len(req.Ids) > 0 {
		client = client.Where("id in (?)", req.Ids)
	}
	if len(req.ManagerIds) > 0 {
		client = client.Where("manager in (?)", req.ManagerIds)
	}
	if req.StartCreateTime > 0 {
		client = client.Where("create_time >= ?", req.StartCreateTime)
	}
	if req.EndCreateTime > 0 {
		client = client.Where("create_time <= ?", req.EndCreateTime)
	}
	var total int64
	if result := client.Count(&total); result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_SELECT_ERROR)
		return
	}

	if total == 0 {
		return
	}

	var models []model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity
	limit, offset := util.FormatLimitAndOffset2Int(req.Limit, req.Offset)
	if err = util.CheckOrderDesc(req.Order, req.Desc); err != nil {
		return
	}
	if len(req.Order) > 0 {
		for i, o := range req.Order {
			client = client.Order(fmt.Sprintf("%s %s", o, req.Desc[i]))
		}
	}
	client = client.Order("id desc")
	result := client.Offset(offset).Limit(limit).Find(&models)
	if result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_SELECT_ERROR)
		return
	}

	list := make([]*proto.UPPER_GO_SERVICE_MODULE_HUMPDetailDataResp, 0, len(models))
	for _, info := range models {
		list = append(list, this.formatDetailData(&info))
	}

	data.Total = total
	data.MaxPage = util.FormatMaxPage(total, int64(limit))
	data.List = list

	return
}

//AddUPPER_GO_SERVICE_MODULE_HUMP GO_SERVICE_MODULE_DESC - 添加
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) AddUPPER_GO_SERVICE_MODULE_HUMP(ctx context.Context, req *proto.AddUPPER_GO_SERVICE_MODULE_HUMPReq) (data *proto.AddUPPER_GO_SERVICE_MODULE_HUMPDataResp, err error) {
	modelEntity := this.buildAddData(req)
	if result := mysql.ClientV2.Create(modelEntity); result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_INSERT_ERROR)
		return
	}

	data = &proto.AddUPPER_GO_SERVICE_MODULE_HUMPDataResp{
		Id: modelEntity.Id,
	}

	return
}

//BatchAddUPPER_GO_SERVICE_MODULE_HUMP GO_SERVICE_MODULE_DESC - 批量添加
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) BatchAddUPPER_GO_SERVICE_MODULE_HUMP(ctx context.Context, req *proto.BatchAddUPPER_GO_SERVICE_MODULE_HUMPReq) (data *proto.BatchAddUPPER_GO_SERVICE_MODULE_HUMPDataResp, err error) {
	batchAddData := make([]*model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity, 0, len(req.List))
	for _, v := range req.List {
		batchAddData = append(batchAddData, this.buildAddData(v))
	}

	err = mysql.ClientV2.CreateInBatches(batchAddData, 500).Error
	if err != nil {
		err = exterr.Wrap(err, exterr.I_MYSQL_INSERT_ERROR)
		return
	}

	data = &proto.BatchAddUPPER_GO_SERVICE_MODULE_HUMPDataResp{}

	return
}

//UpdateUPPER_GO_SERVICE_MODULE_HUMP GO_SERVICE_MODULE_DESC - 更新
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) UpdateUPPER_GO_SERVICE_MODULE_HUMP(ctx context.Context, req *proto.UpdateUPPER_GO_SERVICE_MODULE_HUMPReq) (data *proto.UpdateUPPER_GO_SERVICE_MODULE_HUMPDataResp, err error) {
	if req.Id <= 0 {
		err = exterr.New(exterr.E_PARAM_DROP)
		return
	}
	modelEntity := &model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{}
	client := mysql.ClientV2.Where("id = ?", req.Id)
	//##ROW_STATUS!client = client.Scopes(util.WithRowStatusNormalV2)
	if len(req.ManagerIds) > 0 {
		client = client.Where("manager in (?)", req.ManagerIds)
	}
	client = client.First(modelEntity)
	if client.Error == gormV2.ErrRecordNotFound {
		err = util.FormatAuthError(req.ManagerIds)
		return
	}
	if client.Error != nil {
		err = exterr.Wrap(client.Error, exterr.I_MYSQL_SELECT_ERROR)
		return
	}
	oldData := *modelEntity
	this.buildUpdateData(req, modelEntity)

	if result := mysql.ClientV2.Save(modelEntity); result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_UPDATE_ERROR)
		return
	}

	data = &proto.UpdateUPPER_GO_SERVICE_MODULE_HUMPDataResp{
		Id: modelEntity.Id,
	}
	if req.ReturnNewData {
		data.NewData = this.formatDetailData(modelEntity)
	}
	if req.ReturnOldData {
		data.OldData = this.formatDetailData(&oldData)
	}


	return
}

//BatchUpdateUPPER_GO_SERVICE_MODULE_HUMP GO_SERVICE_MODULE_DESC - 批量更新
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) BatchUpdateUPPER_GO_SERVICE_MODULE_HUMP(ctx context.Context, req *proto.BatchUpdateUPPER_GO_SERVICE_MODULE_HUMPReq) (data *proto.BatchUpdateUPPER_GO_SERVICE_MODULE_HUMPDataResp, err error) {
	// 先找出来所有需要修改的数据
	ids := make([]int64, 0, len(req.GetList()))
	for _, v := range req.GetList() {
		ids = append(ids, v.Id)
	}

	var models []model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity
	err = mysql.ClientV2.Where("id in (?)", ids).Find(&models).Error
	if err != nil {
		err = exterr.Wrap(err, exterr.I_MYSQL_SELECT_ERROR)
		return
	}

	modelMap := make(map[int64]model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity)
	for _, v := range models {
		modelMap[v.Id] = v
	}

	batchArr := make([]interface{}, 0, len(req.GetList()))
	for _, v := range req.GetList() {
		t, ok := modelMap[v.Id]
		if !ok {
			err = exterr.New(exterr.E_DATA_FAIL)
			return
		}

		this.buildUpdateData(v, &t)
		batchArr = append(batchArr, t)
	}

	if len(batchArr) > 0 {
		err = mysql.ClientV2.BatchUpdate(batchArr, "id", nil)
		if err != nil {
			err = exterr.Wrap(err, exterr.I_MYSQL_UPDATE_ERROR)
			return
		}
	}

	data = &proto.BatchUpdateUPPER_GO_SERVICE_MODULE_HUMPDataResp{}

	return
}

//DeleteUPPER_GO_SERVICE_MODULE_HUMP GO_SERVICE_MODULE_DESC - 删除
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) DeleteUPPER_GO_SERVICE_MODULE_HUMP(ctx context.Context, req *proto.DeleteUPPER_GO_SERVICE_MODULE_HUMPReq) (data *proto.DeleteUPPER_GO_SERVICE_MODULE_HUMPDataResp, err error) {
	if req.Id <= 0 {
		err = exterr.New(exterr.E_PARAM_DROP)
		return
	}
	//##LOGIC_ROW_STATUS!return // 没有软删除字段，请自行处理逻辑
	modelEntity := &model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{}
	data = &proto.DeleteUPPER_GO_SERVICE_MODULE_HUMPDataResp{}
	client := mysql.ClientV2.Where("id = ?", req.Id)
	//##ROW_STATUS!client = client.Scopes(util.WithRowStatusNormalV2)
	if len(req.ManagerIds) > 0 {
		client = client.Where("manager in (?)", req.ManagerIds)
	}
	client = client.First(modelEntity)
	if client.Error == gormV2.ErrRecordNotFound {
		err = util.FormatAuthError(req.ManagerIds)
		return
	}
	if client.Error != nil {
		err = exterr.Wrap(client.Error, exterr.I_MYSQL_SELECT_ERROR)
		return
	}
	oldData := *modelEntity

	//##OPERATOR!modelEntity.Operator = req.Operator
	//##ROW_STATUS!modelEntity.RowStatus = consts.RowStatusDel
	//##MODIFY_TIME!modelEntity.ModifyTime = time.Now().Unix()
	if result := mysql.ClientV2.Save(modelEntity); result.Error != nil {
		err = exterr.Wrap(result.Error, exterr.I_MYSQL_UPDATE_ERROR)
		return
	}
	data = &proto.DeleteUPPER_GO_SERVICE_MODULE_HUMPDataResp{
		Id: modelEntity.Id,
	}
	if req.ReturnNewData {
		data.NewData = this.formatDetailData(modelEntity)
	}
	if req.ReturnOldData {
		data.OldData = this.formatDetailData(&oldData)
	}

	return
}

//formatDetailData 格式化单条数据
func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) formatDetailData(info *model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity) *proto.UPPER_GO_SERVICE_MODULE_HUMPDetailDataResp {
	return &proto.UPPER_GO_SERVICE_MODULE_HUMPDetailDataResp{
		FORMAT_DETAIL_DATA_KEY_VEL
	}
}

func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) buildAddData(req *proto.AddUPPER_GO_SERVICE_MODULE_HUMPReq) *model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity {
	modelEntity := &model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity{
		ADD_DATA_KEY_VAL
	}

	return modelEntity
}

func (this UPPER_GO_SERVICE_MODULE_HUMPLogic) buildUpdateData(req *proto.UpdateUPPER_GO_SERVICE_MODULE_HUMPReq, modelEntity *model.ErpUPPER_GO_SERVICE_FULL_TABLE_HUMPEntity) {
	UPDATE_DATA_KEY_VAL

	//##MODIFY_TIME!modelEntity.ModifyTime = time.Now().Unix()
}

